// JavaScript Document
/*
这个脚本控制字幕相关功能，如果不需要字幕则无需加载此脚本。

                                      Noah～～
									  文档最后修改日期：2011-03-01
*/
var script_info=new Array();
var v4plus_styles=new Array();
var events=new Array();

var subtitle_process=new XMLHttpRequest();
function request_subtitle(subtitle_name)
{
  var request_subtitle_name="sub_file_name="+subtitle_name;
  subtitle_process.open("POST","subtitle_xml.php");
  subtitle_process.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  subtitle_process.onreadystatechange=get_xml;
  subtitle_process.send(request_subtitle_name);
}
function get_xml()
{
  if(subtitle_process.readyState==4)
  {
    if(subtitle_process.status==200)
    {
      play_subtitle(subtitle_process.responseXML,html5_player_video_id,html5_player_subtitle_text_place_id);
    }
    else
    {clean_error_subtitle("读取字幕出错");}
  }
  else
  {
    document.getElementById(html5_player_subtitle_text_place_id).innerHTML="正在读取字幕";
  }
}
function play_subtitle(subtitle_xml,video_id,subtitle_place)//字幕播放主调用程序，进行字幕操作预处理
{
  timer=clearInterval(timer);//清除已有的计时器
  remove_css_styles(html5_player_subtitle_css_place_id);
  events=remove_array(events);
  script_info=remove_array(script_info);
  v4plus_styles=remove_array(v4plus_styles);
  
  //清除上一次字幕的设置
  if(document.getElementById(html5_player_subtitle_list_id).value.length!=1)
{
    document.getElementById(html5_player_subtitle_text_place_id).innerHTML="正在渲染字幕";
    var timer=0;
    script_info=make_subtitle(subtitle_xml,1);//生成script info数组 暂时没作用 为以后深度开发保留
    v4plus_styles=make_subtitle(subtitle_xml,2);//生产v4+ styles数组 提取出style的格式
    events=make_subtitle(subtitle_xml,3);//生成events数组 该数组是字幕主体 需要显示到屏幕上的文字  
 	    if(script_info==undefined||v4plus_styles==undefined||events==undefined)//检查字幕处理进程
    {clean_error_subtitle("字幕格式不正确导致XML解析出错");}
    else//字幕正常，设定计时器，调用字幕显示函数
    {
    events=use_styles_to_subtitle(events);//将css id添加到字幕
    make_css_styles(v4plus_styles);//将v4+ styles数组生记录的style信息生成css并添加到html文档中
	show_v4plus_styles(v4plus_styles);//更新显示到字幕样式表
timer=setInterval(function()
{
  locate_subtitle(video_id,subtitle_place,events);
}
,100);

    }
	
}
else//选择了无字幕或没有该字幕
{
document.getElementById(html5_player_subtitle_style_information_id).innerHTML="请选择一个字幕后进行本操作。";//当选择无字幕时无法更新显示样式表，暂时放在这里，有更好的方法后修正
hide_subtitle(subtitle_place);
}

}
function make_subtitle(subtitle_xml,out)//生成字幕要用到的各种数组
{
  var script_info_return=new Array();
  var v4plus_styles_return=new Array();
  var events_return=new Array();
  if(subtitle_xml.documentElement.childNodes.length!=3)//未选择字幕，不进行操作
  {; }
  else
  {
    if(out==1)//生成script info数组的调用
    {
      var script_info_array=subtitle_xml.documentElement.firstChild.childNodes;
      for(a=0;a<script_info_array.length;a++)
      {
        script_info_return[script_info_array[a].nodeName]=script_info_array[a].textContent;
      }
      return script_info_return;
    }
    else if(out==2)//生产v4+ styles数组的调用
    {
      var v4plus_styles_array=subtitle_xml.documentElement.firstChild.nextSibling.childNodes;
      for(var a=0;a<v4plus_styles_array.length;a++)
      {
        var v4plus_styles_array2=v4plus_styles_array[a].childNodes;
        var array_push=new Array();
        for(var b=0;b<v4plus_styles_array2.length;b++)
        {
          array_push[v4plus_styles_array2[b].nodeName]=v4plus_styles_array2[b].textContent;
        }
        v4plus_styles_return.push(array_push);
      }
      return v4plus_styles_return;
    }
    else if(out==3)//生产events数组的调用
    {
      var events_array=subtitle_xml.documentElement.lastChild.childNodes;
      for(var a=0;a<events_array.length;a++)
      {
        var events_array2=events_array[a].childNodes;
        var array_push=new Array();
        for(var b=0;b<events_array2.length;b++)
        {
          array_push[events_array2[b].nodeName]=events_array2[b].textContent.replace("\\N","<br>");//字幕预处理操作，可作为以后深度开发
        }
        events_return.push(array_push);
      }
      return events_return;
    }
  }
}
locate_subtitle=function(video_id,subtitle_place,events_array)//字幕显示主函数，确定时间，定位字幕
{
  var video_time=parseFloat((document.getElementById(video_id).currentTime-0.1)).toFixed(2);//视频当前时间，“-0.1”是为了减少误差值，这个值的大小应与setInterval的时间值一样
  subtitle_text=find_sub(video_time,events_array);//字幕定位
  if(subtitle_text==false||subtitle_text==undefined)
  {
    hide_subtitle(subtitle_place);
  }
  else
  {
    show_subtitle(subtitle_place,subtitle_text);//字幕实时效果显示，作为日后重点深度开发，现在仅返回字幕原始数据，忽略掉字幕特效
  }
}
time_to_second=function(time_string)//时间转换（字符串->数值）
{
  if(time_string!=undefined)
  {
    var time_array=time_string.split(':');
    var time_string_to_second=parseFloat(time_array[0])*60*60+parseFloat(time_array[1])*60+parseFloat(time_array[2]);
    return time_string_to_second;
  }
  else
 {return false;}
}
show_subtitle=function(subtitle_place,subtitle)//显示字幕
{
  if(document.getElementById(subtitle_place).innerHTML!=subtitle)//若字幕没有变化则不做插入
  {
    document.getElementById(subtitle_place).innerHTML=subtitle;
  }
}
hide_subtitle=function(subtitle_place)//隐藏字幕
{
  document.getElementById(subtitle_place).innerHTML="";
}
find_sub=function(time,events_array)//定位字幕，用来确定这个“时刻”该显示哪一条字幕
{
  time=parseFloat(time);
  for(o=0;o<events_array.length;o++)
  {
    if(time>=(time_to_second(events_array[o]["Start"]))&&time<=(time_to_second(events_array[o]["End"])))
    {
      return events_array[o]["Text"];
    }
  }
  return false;
}
make_css_styles=function(css_styles_array)//生成CSS规则字符串并写入html文档
{
var html_subtitle_style=document.getElementById(html5_player_subtitle_css_place_id);
var html_subtitle_css_string="";
 for(var s=0;s<css_styles_array.length;s++)
  {

    html_subtitle_css_string+='.'+css_styles_array[s]["Name"];
	html_subtitle_css_string+='{';
		
	html_subtitle_css_string+='font-family:\"'+css_styles_array[s]["Fontname"]+'\";';
	html_subtitle_css_string+='font-size:'+css_styles_array[s]["Fontsize"]+'px;';
	html_subtitle_css_string+='color:'+ass_color_to_css_color(css_styles_array[s]["PrimaryColour"])+';';
	html_subtitle_css_string+="text-shadow:"+ass_outline_to_css_text_shadow(css_styles_array[s]["Outline"],css_styles_array[s]["OutlineColour"])+";";
	html_subtitle_css_string+="font-weight:"+chk_if_is_bold(css_styles_array[s]["Bold"])+";";
	html_subtitle_css_string+="font-style:"+chk_if_is_italic(css_styles_array[s]["Italic"])+";";
	html_subtitle_css_string+="text-decoration:"+chk_if_is_underline_and_strikeout(css_styles_array[s]["Underline"],css_styles_array[s]["StrikeOut"])+";";
	
	html_subtitle_css_string+="}"//css样式结尾，放在最后。不要在 } 使用分号。
  }
html_subtitle_style.innerHTML=html_subtitle_css_string;
        function chk_if_is_bold(value)//粗体检测
		{
		  if(value==-1)
		  {return "bold";}	
		  else
		  {return "normal";}
		}
		
		function chk_if_is_italic(value)//斜体检测
		{
		  if(value==-1)
		  {return "italic";}	
		  else
		  {return "normal";}
		}
		function chk_if_is_underline_and_strikeout(value_underline,value_strikeout)//下划线和删除线检测
		{
			//"text-decoration: line-through,underline;"
		  if(value_underline==-1 && value_strikeout==-1)
		  {
			 return "line-through underline"; 
		  }	
		  else if(value_underline==-1)
		  {
			  return "underline";
		  }	
		  else if(value_strikeout==-1)
		  {
			  return "line-through";
		  }	
		  else
		  {
			 return "none";//没有的情况下需要使用none，否则不能覆盖已有的规则
		  }
		}
		


  function ass_outline_to_css_text_shadow(shadow_size,shadow_color)//字体轮廓
{
	//text-shadow:2px 2px 2px rgba(0,00,00,0.71),-2px -2px 2px rgba(0,00,00,0.71);
	var text_shadow_srting=shadow_size+"px ";//空格必须有,右轮廓
	text_shadow_srting+=shadow_size+"px ";//下轮廓
	text_shadow_srting+=shadow_blur(shadow_size)+"px ";//轮廓模糊半径
	text_shadow_srting+=ass_color_to_css_color(shadow_color)+",";//轮廓颜色
	text_shadow_srting+="-"+shadow_size+"px ";//左轮廓
	text_shadow_srting+="-"+shadow_size+"px ";//上轮廓
	text_shadow_srting+=shadow_blur(shadow_size)+"px ";
	text_shadow_srting+=ass_color_to_css_color(shadow_color)+"";
	return text_shadow_srting;
	function shadow_blur(size)//生成模糊半径，该值计算方法仅作参考，实际效果仍需调整
	{
		if(size%2!=0)
		{return (size+1)/2;}
		else
		{return size/2;}
	}
}
	function ass_color_to_css_color(ass_color_string)//将V4 styles里的颜色转换为css3的颜色
  {
  var ass_a=ass_color_string.substring(2,4);
  var ass_b=ass_color_string.substring(4,6);
  var ass_g=ass_color_string.substring(6,8);
  var ass_r=ass_color_string.substring(8,10);
  //ASS的颜色:aabbggrr，CSS的颜色：rrggbbaa
  var css_r=sixteen_to_ten(ass_r,"r");
  var css_g=sixteen_to_ten(ass_g,"g");
  var css_b=sixteen_to_ten(ass_b,"b");
  var css_a=sixteen_to_ten(ass_a,"a");
  
  var css3_rgba_string="rgba("+css_r+","+css_g+","+css_b+","+css_a+")";
  return css3_rgba_string;
  
	function sixteen_to_ten(sixteen,type)//十六进制转10进制
	{
		/*
		CSS里的rgba取值范围是：
					   rgba（   r   ,   g   ,   b   ,   a   ）
							 0~255 , 0~255 , 0~255 ,  0~1
			CSS的alpha值最大是1，而V4 style的alpha值最大是255（FF），并且在实际效果上，CSS里alpha为0的效果等于v4 style里alpha为ff的效果
		*/
		if(type=="b"||type=="r"||type=="g")
		{return parseInt(sixteen,16);}
		else if (type=="a")
		{return (1-(parseInt(sixteen,16)/255)).toFixed(2);}
		else
		{return false;}
	}
  
  
  }
}
use_styles_to_subtitle=function(events_array)//给字幕添加css格式，当前作为预处理部分加入，以后应作为实时效果加入
{
  for(var g=0;g<events_array.length;g++)
  {
    var text_head="<span class=\""+events_array[g]["Style"]+"\">";
    var text_end="<\/span>";
    var text=events_array[g]["Text"];
    events_array[g]["Text"]=text_head+text+text_end;
  }
  return events_array;
}
remove_array=function(array_in)//消除数组以供下次使用
{
  for(a=0;a<array_in.length;a++)
  {
    array_in[a]=array_in[a].splice(0,array_in[a].length);
  }
  array_in=array_in.splice(0,array_in.length);
  return array_in;
}
remove_css_styles=function(html_subtitle_style)//删除字幕CSS样式表
{
document.getElementById(html_subtitle_style).innerHTML="";	
}
clean_error_subtitle=function(error_message)
{
	    events=new Array(new Array("Saab","Volvo","BMW"),new Array("Saab","Volvo","BMW"),new Array("Saab","Volvo","BMW"));
        script_info=new Array(new Array("Saab","Volvo","BMW"),new Array("Saab","Volvo","BMW"),new Array("Saab","Volvo","BMW"));
        v4plus_styles=new Array(new Array("Saab","Volvo","BMW"),new Array("Saab","Volvo","BMW"),new Array("Saab","Volvo","BMW"));
		//写入垃圾信息，避免remove_array出错
		alert(error_message);
		document.getElementById(html5_player_subtitle_style_information_id).innerHTML="字幕不正确。";
document.getElementById(html5_player_subtitle_text_place_id).innerHTML="";
		
}

show_v4plus_styles=function(css_styles_array)//显示字幕样式表，供调整
{
	if(css_styles_array.length!=0)
	{
		var style_infos="";//构建表格显示信息
		style_infos+="<table border=\"1\" align=\"center\" >";
		style_infos+="<tr align=\"center\" valign=\"middle\"><td>样式名</td><td>字体</td><td>字体大小(px)</td><td>字体颜色<br>（AABBGGRR）</td><td>轮廓大小(px)</td><td>轮廓颜色<br>（AABBGGRR）</td><td>加粗</td><td>斜体</td><td>下划线</td><td>删除线</td></tr>";
  for(var s=0;s<css_styles_array.length;s++)
  {
	  style_infos+="<tr>";
	  style_infos+="<td>";
	  style_infos+=css_styles_array[s]["Name"];//更改样式名将会导致字幕找不到css，所以不提供修改
	  style_infos+="</td><td>";
	  style_infos+="<input name=\"textfield\" type=\"text\" id=\"style_"+s+"_fontname\" size=\"10\" value=\""+css_styles_array[s]["Fontname"]+"\"/>";//字体名考虑将提供下拉菜单修改
	  style_infos+="</td><td>";
	  style_infos+="<input name=\"textfield\" type=\"text\" id=\"style_"+s+"_fontsize\" size=\"1\" value=\""+css_styles_array[s]["Fontsize"]+"\"/>";//字体大小考虑使用滑动条修改
	  style_infos+="</td><td>";
	  style_infos+="<input type=\"text\" id=\"style_"+s+"_color\" size=\"10\" value=\""+css_styles_array[s]["PrimaryColour"]+"\"";//颜色暂时没有找到好的输入方式，暂以文本框输入
	  style_infos+="</td><td>";
	  
      style_infos+="<input name=\"textfield\" type=\"text\" id=\"style_"+s+"_outline\" size=\"1\" value=\""+css_styles_array[s]["Outline"]+"\"/>";//字体大小考虑使用滑动条修改
	  style_infos+="</td><td>";
	  style_infos+="<input type=\"text\" id=\"style_"+s+"_outlinecolor\" size=\"10\" value=\""+css_styles_array[s]["OutlineColour"]+"\"";//颜色暂时没有找到好的输入方式，暂以文本框输
	  style_infos+="</td><td>";
	  
	  style_infos+=pull_menu("style_"+s+"_bold",css_styles_array[s]["Bold"]);
	  style_infos+="</td><td>";
	  style_infos+=pull_menu("style_"+s+"_italic",css_styles_array[s]["Italic"]);
	  style_infos+="</td><td>";
	  style_infos+=pull_menu("style_"+s+"_underline",css_styles_array[s]["Underline"]);
	  style_infos+="</td><td>";
	  style_infos+=pull_menu("style_"+s+"_strikeout",css_styles_array[s]["StrikeOut"]);
	  style_infos+="</td>";
	  
	  
	  style_infos+="</tr>";
  }
  style_infos+="</table>";
  style_infos+="*更换字幕后设置将重置*";
  style_infos+="<input type=\"button\" name=\"button\" value=\"保存\" onclick=\"set_new_style(v4plus_styles)\"/>";
  document.getElementById(html5_player_subtitle_style_information_id).innerHTML=style_infos;
	  }
	else{
		document.getElementById(html5_player_subtitle_style_information_id).innerHTML="未选择字幕。";//这个方法失效了，暂时在更换字幕的function里做
		}

    	function pull_menu(id,value)//生成带默认选项的下拉菜单，仅用于粗体、斜体、下划线和删除线
		{
		var menu_string="<select id=\""+id+"\">";
		menu_string+="<option value=\"-1\" "+if_is_default_select(value,-1)+">是</option>";
		menu_string+="<option value=\"0\" "+if_is_default_select(value,0)+">否</option>";
		menu_string+="<\/select>";
		return menu_string;
		
		   function if_is_default_select(real_value,chk_value)
		   {
			   if(real_value==chk_value)
			  { return "selected";}
			   else
			   {return "";}
		   }
		}
	
		
}

set_new_style=function(old_css_style_array)//设置新的css格式
{
	  for(var a=0;a<old_css_style_array.length;a++)//从新的样式表收集数据写入v4_styles数组
	  {
	  old_css_style_array[a]["Fontname"]=document.getElementById("style_"+a+"_fontname").value;
	  old_css_style_array[a]["Fontsize"]=chk_is_num(document.getElementById("style_"+a+"_fontsize").value);
	  old_css_style_array[a]["PrimaryColour"]=document.getElementById("style_"+a+"_color").value;
	  old_css_style_array[a]["Outline"]=chk_is_num(document.getElementById("style_"+a+"_outline").value);
	  old_css_style_array[a]["OutlineColour"]=document.getElementById("style_"+a+"_outlinecolor").value;
	  old_css_style_array[a]["Bold"]=document.getElementById("style_"+a+"_bold").value;
	  old_css_style_array[a]["Italic"]=document.getElementById("style_"+a+"_italic").value;
	  old_css_style_array[a]["Underline"]=document.getElementById("style_"+a+"_underline").value;
	  old_css_style_array[a]["StrikeOut"]=document.getElementById("style_"+a+"_strikeout").value;
	  }
	  
make_css_styles(old_css_style_array); 

  function chk_is_num(chk_in)//对字体大小进行检查
  {
	  chk_in=parseInt(chk_in);
	if(isNaN(chk_in)||chk_in==null||chk_in<=0)
	{alert("大小必须为正整数");}
	else
	{return chk_in;}
  }
}
